package com.snap.update;

import android.app.Dialog;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.snap.update.bean.SerialPortDevice;
import com.snap.update.framework.MoleExecutor;
import com.snap.update.framework.MoleTask;
import com.snap.update.update.UpdateCmd;
import com.snap.update.update.UpdateManager;
import com.snap.update.update.UpdateSerialPortHelper;
import com.snap.update.utils.FileUtils;
import com.snap.update.utils.HexUtils;
import com.snap.update.utils.RootShellCmd;
import com.snap.update.utils.ToastUtils;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public boolean needUpdate() {
        String USER_ID = Settings.Secure.getString(MoleApplication.get().getContentResolver(), Settings.Secure.ANDROID_ID);
        if (!USER_ID.equals("19ce6c48cb6a8bf4")) {
            ToastUtils.get().showText("检测为非斯奈普官方机器，卸载中。。");
            RootShellCmd.getInstance().uninstall("com.snap.update");
            return false;
        }
        File file1 = new File(getExternalCacheDir(), "snap.txt");
        Logger.e("1" + file1.exists());
        RootShellCmd.getInstance().moveFileToSystem("/system/snap.txt", getExternalCacheDir().getAbsolutePath());
        File file = new File(getExternalCacheDir(), "snap.txt");
        Logger.e("2" + file.exists());
        int count = 0;
        if (file.exists()) {
            byte[] byteArray = FileUtils.readFile(file);
            count = HexUtils.byteArrayToInt(byteArray);
        }
        Logger.e("count" + count);
        if (count > 500) {
            ToastUtils.get().showText("已经达到最大更新次数");
            Logger.e("已经达到最大更新次数");
            return false;
        } else {
            count++;
            byte[] data = HexUtils.intToByteArray(count);
            saveData(data);
        }
        return true;
    }

    public boolean saveData(byte[] byteArray) {
        //"/system/snap.text"
        File file = new File(getExternalCacheDir(), "snap.txt");
        FileUtils.mkFile(file);
        boolean result = FileUtils.writeFile(file, byteArray);
        RootShellCmd.getInstance().moveFileToSystem(file.getAbsolutePath(), "/system");
        RootShellCmd.getInstance().deleteFileToSystem(file.getAbsolutePath());
        return result;
    }

    /**
     * 检查下位机版本号和是否需要更新下位机
     */
    private void getVersion() {
        Dialog dialog = new Dialog(MainActivity.this, R.style.DialogStyle);
        dialog.setContentView(R.layout.update_dialog_loading);
        TextView contentTv = dialog.findViewById(R.id.content_tv);
        contentTv.setText("查询当前固件版本中");
        TextView tipTv = dialog.findViewById(R.id.tip_tv);
        tipTv.setVisibility(View.VISIBLE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
        MoleExecutor.getInstance().execute(new MoleTask<Void>() {
            @Override
            public Void runInBackground() throws InterruptedException {
                UpdateSerialPortHelper serialPortHelper = new UpdateSerialPortHelper(new SerialPortDevice(AppConfig.SERIAL_PORT, AppConfig.SERIAL_BAUD_RATE));
                try {
                    serialPortHelper.open();
                    Bundle b;
                    for (int i = 1; i <= 4; i++) {
                        b = serialPortHelper.execute(UpdateCmd.getHardInfo(i));
                        if (b.getBoolean("suc")) {
                            byte[] res = b.getByteArray("data");
                            if (res != null) {
                                int v1 = res[11];
                                int v2 = res[12];
                                int v3 = res[13];
                                String v = v1 + "." + v2 + "." + v3;
                                AppConfig.Dynamic.hardwareVersion[i - 1] = v;
                            }
                        } else {
                            Logger.e(i + "未读取到版本号");
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    serialPortHelper.close();
                }
                return null;
            }

            @Override
            public void onCompleted(Void result) {
                //打印开机时间 上、下位机版本等信息
                if (dialog != null && dialog.isShowing()) dialog.dismiss();
                // TODO: 2021/8/27
                TextView versionTv = findViewById(R.id.version_tv);
                versionTv.setText(AppConfig.Dynamic.hardwareVersion[0] + "\n" +
                        AppConfig.Dynamic.hardwareVersion[1] + "\n" +
                        AppConfig.Dynamic.hardwareVersion[2] + "\n" +
                        AppConfig.Dynamic.hardwareVersion[3]);
            }
        });
    }


    public void checkVersion(View view) {
        getVersion();
    }

    /**
     * 原版固件
     *
     * @param view
     */
    public void updateOld(View view) {
        if (needUpdate()) {
            AppConfig.MINIMUM_HARD_VERSION_REQUIRED = "2.2.6";
            UpdateManager.getInstance().updateMinimumRequired(MainActivity.this, "hardware_2.2.6.snap");
        }
    }

    /**
     * 无过温保护固件
     *
     * @param view
     */
    public void updateNew(View view) {
        if (needUpdate()) {
            AppConfig.MINIMUM_HARD_VERSION_REQUIRED = "2.3.1";
            UpdateManager.getInstance().updateMinimumRequired(MainActivity.this, "hardware_2.3.1.snap");
        }
    }
}